/*
Author : Nguyen Van Ty
Email  : ngvanty_03@yahoo.com
Date   : 6/11/2011 

*/

using System;
using System.Collections.Generic;
using System.Text;
using log4net;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Common;
using BusinessObject;
using Utility;
using System.Xml;        
namespace DataAccessLayer{
      /// <summary>
    /// Define SubCategoryDaoBase class. This class user for DataAccessLayer, contain 4 function Insert, Update, Search, Delete.
    /// If you want add new function, you must define in SubCategoryDao class , not here.
    /// </summary>
    public class SubCategoryDaoBase {
    private static ILog logger = null;
            #region Constructor
             /// <summary>
            /// Define Constructor.
             /// </summary>
            public SubCategoryDaoBase(){}
             static SubCategoryDaoBase()
            {
            //Init logger.
            logger = LoggingUtility.GetLogger(typeof(SubCategoryDaoBase).FullName);
            }
 #endregion
              /// <summary>
             /// Read data from IDataReader, convert to SubCategory Object.
            /// </summary>
            private static SubCategory GetSubCategoryByDataReader(IDataReader reader)
    {
      String methodName = "GetSubCategoryByDataReader";
      if (logger.IsDebugEnabled)
      {
        LoggingUtility.logMethodEntry(logger, methodName);
      }
        try
      {
        SubCategory result = new SubCategory();
              //read SubCategoryId field data.
             
            result.SubCategoryId=ManagerDao.GetintDataFromDataReader(reader,"SubCategoryId");
            
              //read CategoryId field data.
             
            result.CategoryId=ManagerDao.GetstringDataFromDataReader(reader,"CategoryId");
            
              //read SubCategoryCode field data.
             
            result.SubCategoryCode=ManagerDao.GetstringDataFromDataReader(reader,"SubCategoryCode");
            
              //read Published field data.
             
            result.Published=ManagerDao.GetstringDataFromDataReader(reader,"Published");
            
              //read Order field data.
             
            result.Order=ManagerDao.GetintDataFromDataReader(reader,"Order");
            result.SubCategory_TransCollection=SubCategory_TransDao.GetAllLanguageofItem(result.SubCategoryId);
             return result;
      }
      catch (Exception e)
      {
        // write error to log file.
        logger.Error(methodName, e);
        return null;
      }
    }
             /// <summary>
             /// Read data from IDataReader, convert to SubCategoryResult Object.
            /// </summary>
            ///<param name="totalRow"> total of records in table Projects. </param>
         /*   private static SubCategoryResult GetSubCategoryResultByDataReaderByLanguage(IDataReader reader,string LanguageId,ref int totalRow)
    {
      String methodName = "GetSubCategoryResultByDataReader";
      if (logger.IsDebugEnabled)
      {
        LoggingUtility.logMethodEntry(logger, methodName);
      }
        try
      {
        SubCategoryResult result = new SubCategoryResult();
            if (totalRow <= 0)
            {
                ////read TotalRow field data.
                totalRow=ManagerDao.Getint32DataFromDataReader(reader,"TotalRow");              
            }
                //read SubCategoryId field data.
                    result.SubCategoryId =ManagerDao.GetintDataFromDataReader(reader,"SubCategoryId");
            
                //read CategoryId field data.
                    result.CategoryId =ManagerDao.GetstringDataFromDataReader(reader,"CategoryId");
            
                //read SubCategoryCode field data.
                    result.SubCategoryCode =ManagerDao.GetstringDataFromDataReader(reader,"SubCategoryCode");
            
                //read Published field data.
                    result.Published =ManagerDao.GetstringDataFromDataReader(reader,"Published");
            
                //read Order field data.
                    result.Order =ManagerDao.GetintDataFromDataReader(reader,"Order");
            
             return result;
      }
      catch (Exception e)
      {
        // write error to log file.
        logger.Error(methodName, e);
        return null;
      }
    }*/
             /// <summary>
             /// Read data from IDataReader, convert to SubCategoryResult Object.
            /// </summary>
            ///<param name="totalRow"> total of records in table Projects. </param>
         /*   private static SubCategoryResult GetSubCategoryResultByDataReader(IDataReader reader,ref int totalRow)
    {
      String methodName = "GetSubCategoryResultByDataReader";
      if (logger.IsDebugEnabled)
      {
        LoggingUtility.logMethodEntry(logger, methodName);
      }
        try
      {
        SubCategoryResult result = new SubCategoryResult();
            if (totalRow <= 0)
            {
                ////read TotalRow field data.
                totalRow=ManagerDao.Getint32DataFromDataReader(reader,"TotalRow");              
            }
                //read SubCategoryId field data.
                    result.SubCategoryId =ManagerDao.GetintDataFromDataReader(reader,"SubCategoryId");
            
                //read CategoryId field data.
                    result.CategoryId =ManagerDao.GetstringDataFromDataReader(reader,"CategoryId");
            
                //read SubCategoryCode field data.
                    result.SubCategoryCode =ManagerDao.GetstringDataFromDataReader(reader,"SubCategoryCode");
            
                //read Published field data.
                    result.Published =ManagerDao.GetstringDataFromDataReader(reader,"Published");
            
                //read Order field data.
                    result.Order =ManagerDao.GetintDataFromDataReader(reader,"Order");
            
             return result;
      }
      catch (Exception e)
      {
        // write error to log file.
        logger.Error(methodName, e);
        return null;
      }
    }*/
              /// <summary>
        /// Define function Insert for SubCategory Object.
        /// </summary>
        /// <param name="obj">Object Insert.</param>
        /// <returns>
        ///    True: Successfull.
        ///    False: Process Error.
        ///</returns>
            public static bool Insert(SubCategory obj)
            {
               
              String methodName = "InsertSubCategory";
                ManagerDao.BeginTransaction();
              if (logger.IsDebugEnabled)
              {
                LoggingUtility.logMethodEntry(logger, methodName);
              }
              DbCommand cmd = ManagerDao.GetStoredProcCommand("spInsertSubCategory");            
            
                 //Add value "CategoryId"  paramater.
				ManagerDao.AddInParameter(cmd, "CategoryId", DbType.AnsiString,
					ConvertValueObject.CastObjValueToInsertDB(obj.CategoryId));
                 //Add value "SubCategoryCode"  paramater.
				ManagerDao.AddInParameter(cmd, "SubCategoryCode", DbType.AnsiString,
					ConvertValueObject.CastObjValueToInsertDB(obj.SubCategoryCode));
                 //Add value "Published"  paramater.
				ManagerDao.AddInParameter(cmd, "Published", DbType.AnsiString,
					ConvertValueObject.CastObjValueToInsertDB(obj.Published));
                 //Add value "Order"  paramater.
				ManagerDao.AddInParameter(cmd, "Order", DbType.Int32,
					ConvertValueObject.CastObjValueToInsertDB(obj.Order));    
            //add paramater store return value.        
             ManagerDao.AddParameter(cmd, "returnValue", DbType.Int32, ParameterDirection.ReturnValue, string.Empty, DataRowVersion.Default, null);
            try
              {
                ManagerDao.ExecuteNonQuery(cmd);
                Int32 id = Int32.Parse(ManagerDao.GetParameterValue(cmd, "returnValue").ToString());
                if (id>0)//Successfull.
                {
                      if(obj.SubCategory_TransCollection !=null && obj.SubCategory_TransCollection.Count>0)
                      {
                          foreach (SubCategory_Trans o in obj.SubCategory_TransCollection)
                            {
                              if (o!=null)
                              {
                                o.SubCategoryId=id;
                                if(!SubCategory_TransDao.Insert(o))
                                {
                                     ManagerDao.Rollback();  
                                     return false;                                 
                                }
                              }
                              
                            }
                       }
                       ManagerDao.Commit();  
                       return true;   

                }              
              }
              catch (Exception e)
              {
                //write error message to log file.
                logger.Error(methodName, e);              
              }
              ManagerDao.Rollback();  
              return false;                  
            }
             
               /// <summary>
        /// Define function Update for SubCategory Object.
        /// </summary>
        /// <param name="obj">Object Update.</param>
        /// <returns>
        ///    True: Successfull.
        ///    False: Process Error.
        ///</returns>
            public static bool Update(SubCategory obj)
          {
          String methodName = "UpdateSubCategory";
             ManagerDao.BeginTransaction();
          if (logger.IsDebugEnabled)
          {
            LoggingUtility.logMethodEntry(logger, methodName);
          }
             DbCommand cmd = ManagerDao.GetStoredProcCommand("spUpdateSubCategory");
           

                    //Add value "SubCategoryId"  paramater.
				    ManagerDao.AddInParameter(cmd, "SubCategoryId", DbType.Int32,obj.SubCategoryId);
                 //Add value "CategoryId"  paramater.
				ManagerDao.AddInParameter(cmd, "CategoryId", DbType.AnsiString,ConvertValueObject.CastObjValueToInsertDB(obj.CategoryId));
                 //Add value "SubCategoryCode"  paramater.
				ManagerDao.AddInParameter(cmd, "SubCategoryCode", DbType.AnsiString,ConvertValueObject.CastObjValueToInsertDB(obj.SubCategoryCode));
                 //Add value "Published"  paramater.
				ManagerDao.AddInParameter(cmd, "Published", DbType.AnsiString,ConvertValueObject.CastObjValueToInsertDB(obj.Published));
                 //Add value "Order"  paramater.
				ManagerDao.AddInParameter(cmd, "Order", DbType.Int32,ConvertValueObject.CastObjValueToInsertDB(obj.Order));           
            // add parameter store return value.
             ManagerDao.AddParameter(cmd, "returnValue", DbType.Int32, ParameterDirection.ReturnValue, string.Empty, DataRowVersion.Default, null);
           try
          {
            ManagerDao.ExecuteNonQuery(cmd);
            int rows = (int)ManagerDao.GetParameterValue(cmd, "returnValue");
            if (rows == 1)//Successfull.
            {
                 if(obj.SubCategory_TransCollection !=null && obj.SubCategory_TransCollection.Count>0)
                      {
                          foreach (SubCategory_Trans o in obj.SubCategory_TransCollection)
                            {
                              if (o!=null)
                              {
                               
                                if(!SubCategory_TransDao.InsertUpdate(o))
                                {
                                     ManagerDao.Rollback();  
                                     return false;                                 
                                }
                              }
                              
                            }
                       }
                       ManagerDao.Commit();  
                       return true;   
            }          

          }
          catch (Exception e)
          {
            //write error Message to log file.
            logger.Error(methodName, e);           
          }
           ManagerDao.Rollback();  
           return false;    
                }
/// <summary>
/// Get Data SubCategory object. 
/// </summary>
/// <param name="subCategoryId" >This is primary key to get data.</param>
/// <returns>SubCategory object.</returns>
              
           public static SubCategory Get(int subCategoryId)
    {
      String methodName = "GetSubCategory";
      if (logger.IsDebugEnabled)
      {
        LoggingUtility.logMethodEntry(logger, methodName);
      }
      try
      {
        SubCategory result = null;
        DbCommand dbCommnand = ManagerDao.GetStoredProcCommand("spGetSubCategory");
                 //Add value "SubCategoryId"  paramater.
				ManagerDao.AddInParameter(dbCommnand, "SubCategoryId", DbType.Int32,subCategoryId);
        IDataReader reader = ManagerDao.ExecuteReader(dbCommnand);
        if (reader.Read())
        {
          result= GetSubCategoryByDataReader(reader);

        }
        reader.Close();
        return result;
      }
      catch (System.Exception e)
      {
        //write error message to log file.
        logger.Error("Get", e);
        return null;
      }
    }
              /// <summary>
        /// Get All SubCategory object from table SubCategory.
        /// </summary>
        /// <returns>List SubCategory object.</returns>
             public static List<SubCategoryResult> GetAll()
                {
                 String methodName = "GetAll";
      if (logger.IsDebugEnabled)
      {
        LoggingUtility.logMethodEntry(logger, methodName);
      }

      try
      {
        List<SubCategoryResult> listSubCategory = new List<SubCategoryResult>();
        DbCommand dbCommand = ManagerDao.GetStoredProcCommand("spGetAllSubCategory");

        using (IDataReader reader = ManagerDao.ExecuteReader(dbCommand))
        {
          while (reader.Read())
          {
            listSubCategory.Add(GetSubCategoryResultByDataReader(reader));
          }
          reader.Close();
        }

        return listSubCategory;
      }
      catch (Exception ex)
      {
        //write error message to log file.
        logger.Error(methodName, ex);
        return null;
      }
    }

             /// <summary>
        /// Search SubCategory object in table SubCategory with condition is t object.
        /// </summary>
        /// <param name="t">Condition for Search.</param>
        /// <param name="pageIndex">pageindex is postion to begin get data.</param>
        /// <param name="pageSize"> Number of records will be returned. </param>
        /// <param name="totalRow">  total records in this table.</param>
        /// <returns>List SubCategoryResult object.</returns>
           /*  public static List<SubCategoryResult> SearchSubCategorySomeCondition(SubCategoryCondition t, int pageIndex, int pageSize,ref int totalRow)
                {
                 String methodName = "SearchSubCategorySomeCondition";
      if (logger.IsDebugEnabled)
      {
        LoggingUtility.logMethodEntry(logger, methodName);
      }

      try
      {
        List<SubCategoryResult> listSubCategory = new List<SubCategoryResult>();
        DbCommand cmd = ManagerDao.GetStoredProcCommand("spSearchSubCategoryByCondition");
                    //Add value "SubCategoryId"  paramater.
				ManagerDao.AddInParameter(cmd, "SubCategoryId", DbType.Int32,
					ConvertValueObject.CastObjValueToInsertDB(t.SubCategoryId));
                    //Add value "CategoryId"  paramater.
				ManagerDao.AddInParameter(cmd, "CategoryId", DbType.AnsiString,
					ConvertValueObject.CastObjValueToInsertDB(t.CategoryId));
                    //Add value "SubCategoryCode"  paramater.
				ManagerDao.AddInParameter(cmd, "SubCategoryCode", DbType.AnsiString,
					ConvertValueObject.CastObjValueToInsertDB(t.SubCategoryCode));
                    //Add value "Published"  paramater.
				ManagerDao.AddInParameter(cmd, "Published", DbType.AnsiString,
					ConvertValueObject.CastObjValueToInsertDB(t.Published));
                    //Add value "Order"  paramater.
				ManagerDao.AddInParameter(cmd, "Order", DbType.Int32,
					ConvertValueObject.CastObjValueToInsertDB(t.Order));
                //Add value SortField  paramater.
				ManagerDao.AddInParameter(cmd,"SortField", DbType.String,
				ConvertValueObject.CastObjValueToInsertDB(t.SortField));
                //Add value SortExpression  paramater.
                ManagerDao.AddInParameter(cmd,"SortExpression", DbType.String,
				ConvertValueObject.CastObjValueToInsertDB(t.SortExpression));                
                
                 //Add value PageIndex  paramater.
                ManagerDao.AddInParameter(cmd, "PageIndex", DbType.Int32, pageIndex);
                //Add value PageSize  paramater.
                ManagerDao.AddInParameter(cmd, "PageSize", DbType.Int32, pageSize);
          using (IDataReader reader = ManagerDao.ExecuteReader(cmd))
        {
          while (reader.Read())
          {
            listSubCategory.Add(GetSubCategoryResultByDataReader(reader,ref totalRow));
          }
          reader.Close();
        }

        return listSubCategory;
      }
      catch (Exception ex)
      {
        //write error message to log file.
        logger.Error(methodName, ex);
        return null;
      }
    }*/
/// <summary>
/// Delete SubCategory object. 
/// </summary>
/// <param name="SubCategoryId" >This is primary key to delete.</param>
/// <returns>True/False.</returns>

            public static bool Delete(int SubCategoryId)
    {
      String methodName = "DeleteSubCategory";
      if (logger.IsDebugEnabled)
      {
        LoggingUtility.logMethodEntry(logger, methodName);
      }

      try
      {
        DbCommand dbCommand = ManagerDao.GetStoredProcCommand("spDeleteSubCategory");
                //Add value "SubCategoryId"  paramater.
				ManagerDao.AddInParameter(dbCommand, "SubCategoryId", DbType.Int32,SubCategoryId);        
         //Add value returnValue  paramater.
        ManagerDao.AddParameter(dbCommand, "returnValue", DbType.Int32, ParameterDirection.ReturnValue, string.Empty, DataRowVersion.Default, null);
        try
        {
          ManagerDao.ExecuteNonQuery(dbCommand);        
          int parameterValue = (int)ManagerDao.GetParameterValue(dbCommand, "returnValue");
          if (parameterValue == 1)
          {
            return true;
          }
        }
        catch (Exception)
        {
          throw;
        }
        return false;
      }
      catch (Exception e)
      {
        //write error message to log file.
        logger.Error(methodName, e);
        return false;
      }
    }
            /// <summary>
             /// Read data from IDataReader, convert to SubCategoryResult Object.
            /// </summary>
            private static SubCategoryResult GetSubCategoryResultByDataReaderByLanguage(IDataReader reader,string LanguageId)
    {
      String methodName = "GetSubCategoryResultByDataReader";
      if (logger.IsDebugEnabled)
      {
        LoggingUtility.logMethodEntry(logger, methodName);
      }
        try
      {
        SubCategoryResult result = new SubCategoryResult();
            //read SubCategoryId field data.
             result.SubCategoryId =ManagerDao.GetintDataFromDataReader(reader,"SubCategoryId");
            
            //read CategoryId field data.
             result.CategoryId =ManagerDao.GetstringDataFromDataReader(reader,"CategoryId");
            
            //read SubCategoryCode field data.
             result.SubCategoryCode =ManagerDao.GetstringDataFromDataReader(reader,"SubCategoryCode");
            
            //read Published field data.
             result.Published =ManagerDao.GetstringDataFromDataReader(reader,"Published");
            
            //read Order field data.
             result.Order =ManagerDao.GetintDataFromDataReader(reader,"Order");
            
             return result;
      }
      catch (Exception e)
      {
        // write error to log file.
        logger.Error(methodName, e);
        return null;
      }
    }
            /// <summary>
             /// Read data from IDataReader, convert to SubCategoryResult Object.
            /// </summary>
            private static SubCategoryResult GetSubCategoryResultByDataReader(IDataReader reader)
    {
      String methodName = "GetSubCategoryResultByDataReader";
      if (logger.IsDebugEnabled)
      {
        LoggingUtility.logMethodEntry(logger, methodName);
      }
        try
      {
        SubCategoryResult result = new SubCategoryResult();
            //read SubCategoryId field data.
             result.SubCategoryId =ManagerDao.GetintDataFromDataReader(reader,"SubCategoryId");
            
            //read CategoryId field data.
             result.CategoryId =ManagerDao.GetstringDataFromDataReader(reader,"CategoryId");
            
            //read SubCategoryCode field data.
             result.SubCategoryCode =ManagerDao.GetstringDataFromDataReader(reader,"SubCategoryCode");
            
            //read Published field data.
             result.Published =ManagerDao.GetstringDataFromDataReader(reader,"Published");
            
            //read Order field data.
             result.Order =ManagerDao.GetintDataFromDataReader(reader,"Order");
            
             return result;
      }
      catch (Exception e)
      {
        // write error to log file.
        logger.Error(methodName, e);
        return null;
      }
    }  
           
	                }
                }